package com.lemon.boot.service.impl;

import com.lemon.boot.common.base.BaseServiceImpl;
import com.lemon.boot.common.enums.RoleKeyEnum;
import com.lemon.boot.dao.RoleMenuDAO;
import com.lemon.boot.dto.RoleMenuDTO;
import com.lemon.boot.po.RoleMenuPO;
import com.lemon.boot.po.RolePO;
import com.lemon.boot.service.IRoleMenuService;
import com.lemon.boot.service.IRoleService;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色菜单中间表 业务实现类
 *
 * @author Lemon
 * @since 2024-02-29
 */
@Log4j2
@Service
public class RoleMenuServiceImpl extends BaseServiceImpl<RoleMenuDAO, RoleMenuPO, RoleMenuDTO> implements IRoleMenuService {
    @Resource
    @Lazy
    private IRoleService iRoleService;

    @Override
    @Transactional
    public void addByTenantIdMenuId(Long tenantId, List<Long> menuIdList) {
        //1.根据租户ID获取所有角色
        List<RolePO> roleList = iRoleService.getByTenantId(tenantId);
        if (!CollectionUtils.isEmpty(roleList)) {
            //2.获取管理员角色ID
            List<Long> adminRoleIdList = roleList.stream().filter(item -> RoleKeyEnum.ADMIN.getRoleKey().equals(item.getRoleKey())).map(RolePO::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(adminRoleIdList)) {
                //3.给管理员添加 sys_role_menu
                List<RoleMenuPO> roleMenuList = new ArrayList<>();
                for (Long roleId : adminRoleIdList) {
                    for (Long tenantMenuId : menuIdList) {
                        roleMenuList.add(new RoleMenuPO().setTenantMenuId(tenantMenuId).setRoleId(roleId));
                    }
                }
                if (!CollectionUtils.isEmpty(roleMenuList)) {
                    this.saveBatch(roleMenuList);
                }
            }
        }
    }
}